package com.next.aappublicapp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.client.ResourceAccessException;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.google.analytics.tracking.android.EasyTracker;
import com.next.aappublicapp.loaders.FacebookFeedLoader;
import com.next.aappublicapp.server.service.DataServices;
import com.next.aappublicapp.tasks.DownloadImageTaskParam;
import com.next.aappublicapp.util.JsonUtil;
import com.next.aappublicapp.views.FacebookPost;

public class FacebookFeedActivity extends BaseFragmentActivty implements LoaderCallbacks<String>{

	FacebookFeedLoader facebookFeedLoader;
	LinearLayout faceboofFeedMainView;
	LinearLayout faceboofFeedMainViewWrapper;
	LinearLayout facebookFeedProgressBar;
	Button moreFacebookPostButton;
	private Date startTime;
	private String cacheFacebookFeed = null;
	
	private Session.StatusCallback statusCallback = new SessionStatusCallback();
	private UiLifecycleHelper uiHelper;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(MaxFacebookPost == 0){
			MaxFacebookPost = (int) (Runtime.getRuntime().maxMemory() / 1024/1024)/4 ;
			Log.i("Ravi", "MaxFacebookPost="+MaxFacebookPost);
			EasyTracker.getTracker().sendTiming("Aap Server", MaxFacebookPost, "GetFacebookFeed", "MaxFacebookPost");
		}
		
		EasyTracker.getTracker().sendView("Facebook Feed");
		setContentView(R.layout.activity_facebook_feed);
		//facebookFeedLoader = new FacebookFeedLoader(this);
		
		faceboofFeedMainView = (LinearLayout)findViewById(R.id.faceboofFeedMainView);
		faceboofFeedMainViewWrapper = (LinearLayout)findViewById(R.id.faceboofFeedMainViewWraper);
		facebookFeedProgressBar = (LinearLayout)findViewById(R.id.loading_status);
		moreFacebookPostButton = (Button)findViewById(R.id.moreFacebookPostButton);
		Bundle bundle = null;
		//getSupportLoaderManager().initLoader(0, bundle, this);
		
		uiHelper = new UiLifecycleHelper(this, statusCallback);
	    uiHelper.onCreate(savedInstanceState);

		refreshDataFromServer();
		moreFacebookPostButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				EasyTracker.getTracker().sendEvent("Android", "Facebook", "MoreFacebookToNativeApp", 1L);
				String uri = "fb://page/290805814352519";
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
				startActivity(intent);
			}
		});
	}
	/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.facebook_feed, menu);
		return true;
	}
	*/
	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();
	}
	@Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
        //EasyTracker.getInstance().activityStop(this);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("Ravi","onActivityResult = "+requestCode+","+resultCode+","+data);
        //Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }

	private void showWorkingWindow(){
		facebookFeedProgressBar.setVisibility(View.VISIBLE);
		faceboofFeedMainViewWrapper.setVisibility(View.GONE);
	}
	private void hideWorkingWindow(){
		facebookFeedProgressBar.setVisibility(View.VISIBLE);
		faceboofFeedMainViewWrapper.setVisibility(View.GONE);
	}
	@Override
	public Loader<String> onCreateLoader(int id, Bundle args) {
		return facebookFeedLoader;
	}
	public static int MaxFacebookPost = 0;
	private void refreshDataFromServer(){
		if(cacheFacebookFeed == null){
			new AsyncTask<String, String, String>() {
				@Override
				protected String doInBackground(String... params) {
					String facebookFeed = null;
					try{
						if(MaxFacebookPost > 0){
							facebookFeed = DataServices.getInstance().getFacebookFeed(MaxFacebookPost);	
						}else{
							facebookFeed = DataServices.getInstance().getFacebookFeed();
						}
						
					}catch(ResourceAccessException ex){
						Log.e("FacebookFeedLoader","Error in loadInBackground, Unable to connect to Server ",ex);
						ex.printStackTrace();
					}catch(Exception ex){
						Log.e("FacebookFeedLoader","Error in loadInBackground ",ex);
						ex.printStackTrace();
					}finally{
						Date endDate = new Date();
						long totalMillisecondsForNetworkTask = endDate.getTime() - startTime.getTime();
						Log.i("Ravi" ," GetFacebookFeed(Network) Time:" + totalMillisecondsForNetworkTask);
						EasyTracker.getTracker().sendTiming("Aap Server", totalMillisecondsForNetworkTask, "GetFacebookFeed", "Network");
					}
					return facebookFeed;
				}
				@Override
				protected void onPostExecute(String facebookFeed) {
					try{
						cacheFacebookFeed = facebookFeed;
						hideWorkingWindow();
						loadFacebookFeedOnUi(facebookFeed);	
					}finally{
						Date endDate = new Date();
						long totalMillisecondsForUser = endDate.getTime() - startTime.getTime();
						Log.i("Ravi" ," GetFacebookFeed(User) Time:" + totalMillisecondsForUser);
						EasyTracker.getTracker().sendTiming("Aap Server", totalMillisecondsForUser, "GetFacebookFeed", "UserTime");
					}
					
				}
				@Override
				protected void onPreExecute() {
					showWorkingWindow();
					startTime = new Date();
				}
			}.execute();
		}else{
			loadFacebookFeedOnUi(cacheFacebookFeed);
		}
		
		
	}
	
	private void loadFacebookFeedOnUi(String jsonResult){
		if(jsonResult == null){
			facebookFeedProgressBar.setVisibility(View.GONE);
			faceboofFeedMainViewWrapper.setVisibility(View.VISIBLE);
			return;
		}
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonResult);
			JSONArray entriesArray = jsonObject.getJSONArray("data");
			JSONObject onePost;
			FacebookPost oneFacebookPost;
			List<DownloadImageTaskParam> downloadImageTaskParams = new ArrayList<DownloadImageTaskParam>();
			for(int i=0;i<entriesArray.length();i++){
				if(i >=MaxFacebookPost){
					break;
				}
				onePost = entriesArray.getJSONObject(i);
				if(JsonUtil.getSringFromJsonObject(onePost, "message") == null){
					continue;
				}
				oneFacebookPost = new FacebookPost(this, onePost, downloadImageTaskParams, null);
				faceboofFeedMainView.addView(oneFacebookPost);
			}
			//new DownloadImageListTask(downloadImageTaskParams).execute();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			facebookFeedProgressBar.setVisibility(View.GONE);
			faceboofFeedMainViewWrapper.setVisibility(View.VISIBLE);

		}
	}
	@Override
	public void onLoadFinished(Loader<String> arg0, String jsonResult) {
		loadFacebookFeedOnUi(jsonResult);
		
	}

	@Override
	public void onLoaderReset(Loader<String> arg0) {

	}

	private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
        	//Do nothing
        }
    }
}
